<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 资源位操作类 permissionHandler
 * @package  htdocs
 * @subpackage  quanliadmin
 * create by allen.qiang
 * @version 1.0
 * =================================================================
 * @param $dbca                          DBCA
 * =================================================================
 * @abstract searchPermission()          查询权限信息
 * @abstract editPermission()            编辑、新增权限
 * @abstract getPermissionGroup()        获得所有的权限组
 * @abstract getOnePermission()          获得一条权限信息
 * @abstract deletePermission()          删除权限信息
 * =================================================================
 */

class permissionHandler{
	private $dbca;
	
	//构造函数
	public function __construct(&$_dbca){
		$this->dbca = $_dbca;
	}
	
	//析构函数
	public function __destruct(){
		
	}
		
	//新增、编辑权限
	/*
	 * @abstract editPermission() 编辑、新增权限信息
	 * @param    $importData = array(必传：operFlg,permissionID,permissionGroupID,permissionGroupName,
 	 * 								   	  permissionName,permissionRequest
	 * 							   	  可选：creator(新增必传),editor(修改必传),orignalPermissionID(原权限号，修改必传))
	 * @return   array('code','message')
	 *  */
	public function editPermission( $importData ){
		//错误信息
		$error = '';
		$uuid = null;
		
		/* 传入数据有效性验证start */
		//没有传入数据
		if (empty($importData)) $error .= '没有传入任何数据<br/>';
		
		if (!isset($importData['operFlg'])){
			$error .= '未传入operFlg<br/>';
		}
		
		//operFlg：2，新增；3，修改
		if ($importData['operFlg'] != 2 && $importData['operFlg'] != 3) {
			$error .= '传入operFlg错误<br/>';
		}
		
		if ($importData['operFlg'] == 2 && !isset($importData['creator'])) {
			$error .= '创建人不能为空<br/>';
		}
		
		if ($importData['operFlg'] == 3 && !isset($importData['editor'])) {
			$error .= '修改人不能为空<br/>';
		}
		
		if (!isset($importData['permissionID'])) {
			$error .= '权限号不能为空<br/>';
		}
		
		if (!isset($importData['permissionGroupID'])) {
			$error .= '权限组号不能为空<br/>';
		}
		
		if (!isset($importData['permissionGroupName'])) {
			$error .= '权限组名称不能为空<br/>';
		}
		
		if (!isset($importData['permissionName'])) {
			$error .= '权限名称不能为空<br/>';
		}
		
		if (!isset($importData['permissionRequest'])) {
			$error .= '权限路径不能为空<br/>';
		}
		
		if ($importData['operFlg'] == 3 && !isset($importData['orignalPermissionID'])) {
			$error .= '原权限号传值错误<br/>';
		}
		
		if (!empty($error)){
			return array('code' => 400, 'message' => $error);
		}
		/* 传入数据有效性验证end */
		
		$operFlg = $importData['operFlg'];//operFlg
		$creator = $importData['creator'];//创建人
		$editor = $importData['editor'];//修改人
		$permissionID = trim($importData['permissionID']);//权限号
		$permissionGroupID = trim($importData['permissionGroupID']);//权限组号
		$permissionGroupName = trim($importData['permissionGroupName']);//权限组名
		$permissionName = trim($importData['permissionName']);//权限名
		$permissionRequest = trim($importData['permissionRequest']);//权限路径
		$orignalPermissionID = trim($importData['orignalPermissionID']);//原权限ID
			
		/* 组装需进行数据库验证的数组start */
		//需校验的数据
		$needCheck = array('permissionID' => '',
						   'permissionGroupID' => '',
						   'permissionGroupName' => '',
						   'permissionName' => '',
						   'permissionRequest' => '');
		
		//根据原权限号获取原权限号对应的信息
		if ($operFlg == 3 && !empty($orignalPermissionID)){
			$result_onePermission = self::searchPermission(array('permissionID'=>$orignalPermissionID));
			if ($result_onePermission['code'] == 200)
				$onePermission = $result_onePermission['message']['data'];
		}
		
		switch ($operFlg){
			case 2://新增
				$needCheck['permissionID'] = $permissionID;
				$needCheck['permissionGroupID'] = $permissionGroupID;
				$needCheck['permissionGroupName'] = $permissionGroupName;
				$needCheck['permissionName'] = $permissionName;
				$needCheck['permissionRequest'] = $permissionRequest;
				break;
			case 3://修改
				//根据修改前后数据是否相同进行判断，相同则不传入检验数组$needCheck，不同则将修改后的数据传入$needCheck
				if (!empty($onePermission)){
					$needCheck['permissionID'] = ($onePermission[0]->permissionID == $permissionID) ? '' : $permissionID;
					$needCheck['permissionGroupID'] = ($onePermission[0]->permissionGroupID == $permissionGroupID) ? '' : $permissionGroupID;
					$needCheck['permissionGroupName'] = ($onePermission[0]->permissionGroupName == $permissionGroupName) ? '' : $permissionGroupName;
					$needCheck['permissionName'] = ($onePermission[0]->permissionName == $permissionName) ? '' : $permissionName;
					$needCheck['permissionRequest'] = ($onePermission[0]->permissionRequest == $permissionRequest) ? '' : $permissionRequest;
					$uuid = $onePermission[0]->uuid;
				}else {
					$error .= '该页面已过期，请刷新页面';
					return array('code' => 400, 'message' => $error);
				}
				break;
		}
		/* 组装需进行数据库验证的数组end */
		
		/* 数据库验证start */
		//数据库验证
		$sqlStr = 'select permissionID,permissionGroupID,permissionGroupName,permissionName,permissionRequest
			       from user_permission';
		
		$result = $this->dbca->execute($sqlStr);
		
		while (!!$_rs = $result->fetch_object()) {
			if($needCheck['permissionID'] == $_rs->permissionID){
				$error .= '权限号['.$needCheck['permissionID'].']已存在<br/>';
			}
			if($needCheck['permissionRequest'] == $_rs->permissionRequest){
				$error .= '权限路径['.$needCheck['permissionRequest'].']已存在<br/>';
			}
			if($needCheck['permissionGroupID'] != '' && $needCheck['permissionGroupID'] == $_rs->permissionGroupID){//同组权限名称不能重复
					
				if($needCheck['permissionName'] == $_rs->permissionName){
					$error .= '权限名称['.$needCheck['permissionName'].']已存在<br/>';
				}
					
			}
			//新建组名不能重复
			if($needCheck['permissionGroupID'] == '' && $needCheck['permissionGroupName'] == $_rs->permissionGroupName){
				$error .= '权限组名['.$needCheck['permissionGroupName'].']不能重复';
			}
		}
		/* 数据库验证end */
		
		if (!empty($error)){
			return array('code' => 400, 'message' => $error);
		}
				
		//根据本组已有的最大排序号+1给新增的权限添加排序号
		$sql = "select max(sortOrder) maxso from user_permission where permissionGroupID=$permissionGroupID";
		$result = $this->dbca->execute($sql);
		$sortOrder = $result->fetch_object()->maxso+1;

		/* 保存到数据库 */
		try {
			
			$permission = new entity('user_permission');
			$permission->uuid = $uuid;
			if ($this->dbca->fetch($permission)){
				$permission->timeStamp = date('Y-m-d H:i:s');
				$permission->editor = $editor;
					
			}else {
				$permission->creator = $creator;
				$permission->createTime = date('Y-m-d H:i:s');
				$permission->sortOrder = $sortOrder;
					
			}
			$permission->permissionID = $permissionID;
			$permission->permissionName = $permissionName;
			$permission->permissionRequest = $permissionRequest;
			$permission->permissionGroupID = $permissionGroupID;
			$permission->permissionGroupName = $permissionGroupName;
	
			$this->dbca->save($permission, 'project');
	
			if ($operFlg == 2)
				return array( 'code' => 200, 'message' => '保存成功' );
			elseif ($operFlg == 3)
				return array( 'code' => 200, 'message' => '修改成功' );
	
		}catch (Exception $e){
	
			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );
	
		}
	}
	
	//查找权限
	/* 
	 * @abstract searchPermission() 查询权限信息
	 * @param    $importData = array(可选：permissionGroupID,permissionID,rp,page,sortname,sortorder)
	 * @return   $return_data('code','message'=>('data','total'));
	 *  */
	public function searchPermission( $importData=array() ){
		//返回数组
		$return_data = array();
		
		//错误信息
		$error = '';
		
		/* 传入数据有效性验证start */
		if (isset($importData['permissionGroupID']) && !empty($importData['permissionGroupID']) && !is_numeric($importData['permissionGroupID'])){
			$error .= '权限组号必须为数字<br/>';
		}
		
		if (isset($importData['permissionID']) && !empty($importData['permissionID']) && !is_numeric($importData['permissionID'])){
			$error .= '权限号必须为数字<br/>';
		}
		
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error .= '当前页码必须为数字<br/>';
		}
		
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error .= '每页记录数必须为数字<br/>';
		}
		
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		/* 传入数据有效性验证end */
		
		$permissionGroupID = isset($importData['permissionGroupID']) ? $importData['permissionGroupID'] : '';//权限组ID
		$permissionID = isset($importData['permissionID']) ? $importData['permissionID'] : '';//权限ID
		$page = isset($importData['page']) ? $importData['page'] : '';//当前页
		$rp = isset($importData['rp']) ? $importData['rp'] : '';//每页记录数
		$sortname = isset($importData['sortname']) ? $importData['sortname'] : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? $importData['sortorder'] : '';//排序方式
		
		if (!empty($error)){
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error;
			return $return_data;
		}
			
		//求总记录数
		$sql_count = 'SELECT COUNT(pp.permissionID) countNum FROM user_permission pp';
		
		//查询SQL语句（注：表中的sortOrder另命名为orderNum）
		$sql_search = 'SELECT su.trueName creatorName, ss.trueName editorName, pp.permissionID, pp.permissionName,
			       	   pp.permissionRequest, pp.permissionGroupID, pp.permissionGroupName, pp.sortOrder orderNum,
				       pp.creator, pp.editor, pp.uuid, pp.createTime, pp.timeStamp
				       FROM user_permission pp
			           LEFT JOIN s_user su ON su.userID = pp.creator
				       LEFT JOIN s_user ss ON ss.userID = pp.editor';
		
		//排序
		$str_order = '';
		
		//分页
		$str_limit = '';
		
		//查询条件
		$str_search = ' WHERE';
		
		//查询参数类型
		$type_search = '';
		
		//查询参数数组
		$param_search = array();
					
		//查询条件：权限组ID
		if (!empty($permissionGroupID)){
			$str_search .= ' AND pp.permissionGroupID = ?';
			$type_search .= 'i';
			$param_search[] = $permissionGroupID;
		}
		
		//查询条件：权限ID
		if (!empty($permissionID)){
			$str_search .= ' AND pp.permissionID = ?';
			$type_search .= 'i';
			$param_search[] = $permissionID;
		}
		
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
		
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
		
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
		}
		
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
		
		if ($value_count){

			$return_data['code'] = 200;
			
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;
				
			//得到查询结果
			$return_data['message']['data'] = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
			
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
		
		return $return_data;
	}
	
	//查找所有权限组
	/*
	 * @abstract getPermissionGroup() 查询所有的权限组
	 * @return   $item_array
	 *  */
	public function getPermissionGroup(){
		$sql = 'SELECT DISTINCT permissionGroupID, permissionGroupName FROM user_permission';
		$item_array = $this->dbca->stmt_query($sql);
		return $item_array;
	}
	
	//删除权限
	/*
	 * @abstract deletePermission()   删除权限
	 * @param    $permissionID_arr    permissionID组成的数组
	 * @return   array('code','message')
	 *  */
	public function deletePermission( $permissionID_arr ){
		
		$error = '';
		
		if (empty($permissionID_arr)){
			$error = '请选择至少一条要删除的数据<br/>';
			return array('code' => 400, 'message' => $error);
		}

		try {
			
			foreach ($permissionID_arr as $permissionID_list){
				
				if (!is_numeric($permissionID_list)){
					return array('code' => 400, 'message' => 'permissionID传值错误');
				}
				
				$permission_obj = new entity('user_permission');
				
				$permission_obj->permissionID = $permissionID_list;
				
				if ($this->dbca->fetch($permission_obj)) {
					$this->dbca->delete($permission_obj);
				}
			}
				
			return array( 'code' => 200, 'message' => '删除成功' );
				
		}catch (Exception $e){
			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '页面过期，请刷新页面' );
		}
		
	}
	
}